/**
 * Created by spatra on 14-9-8.
 */

define(function() {
	var Render = function (canvas, drawType, imgSrc) {

		this.canvas = canvas;
		this.canvasContext = canvas.getContext('2d');
		this.useBufferCanvas = this.initBufferCanvas();

		this.drawType = drawType;
		this.drawTypes = {};
		this._initDrawTypes();

		this.imgSrc = imgSrc;
	};

	Render.prototype = {
		constructor: Render,

		/**
		 * 开始绘制.
		 *
		 * @param entities 待绘制的实体
		 * @param drawType 绘制所采用的方法名称
		 */
		draw: function (entities, drawType) {

			drawType = drawType || this.drawType;

			this.canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);

			for (var i = 0; i != entities.getLength(); ++i) {
				( this.drawTypes[ drawType ] ).call(this, entities.get(i), this.useBufferCanvas.context);
			}

			this.useBufferCanvas.draw();
			console.log('use buffer');
		},

		/**
		 * 添加绘图方法。
		 *
		 * @param name 新增方法的名称
		 * @param funObj 新增方法的函数对象，该对象将会被Render对象调用(this指向Render对象)
		 */
		addDrawType: function(name, funObj){
			if( typeof(funObj) === 'function' ){
				this.drawTypes[ name ] = funObj;
			}
		},

		/**
		 * 初始化默认的绘图方法.
		 *
		 * @private
		 */
		_initDrawTypes: function(){

			this.addDrawType('simple', function(theEntity, drawContext){
				drawContext = drawContext || this.canvasContext;

				drawContext.beginPath();
				drawContext.arc(theEntity.x, theEntity.y,
					theEntity.radius, 0, Math.PI * 2,
					false);

				if( theEntity.collision ){
					drawContext.fillStyle = '#c00';
					theEntity.collision = false;
				}
				else{
					drawContext.fillStyle = '#ccc';
				}

				if(theEntity.dragStatus ){
					drawContext.fillStyle = '#03C';
				}

				drawContext.fill();
				drawContext.closePath();
			});


			this.addDrawType('image', function(theEntity, drawContext){

				drawContext = drawContext || this.canvasContext;

				var ballImg = new Image();
				ballImg.src = this.imgSrc;
				drawContext.drawImage(ballImg, theEntity.x, theEntity.y, theEntity.radius * 2, theEntity.radius * 2);
			});
		},

		/**
		 * 初始化双缓冲策略的操作对象.
		 *
		 * @returns {{context: CanvasRenderingContext2D, draw: draw}}
		 */
		initBufferCanvas: function(){
			var bufferCanvas = document.createElement('canvas');
			bufferCanvas.width = this.canvas.width;
			bufferCanvas.height = this.canvas.height;

			var theCanvasContent = this.canvasContext;
			var bufferCanvasContent = bufferCanvas.getContext('2d');
			return {
				context: bufferCanvasContent,
				draw: function(){
					theCanvasContent.drawImage(bufferCanvas, 0, 0);
					bufferCanvasContent.clearRect(0, 0, bufferCanvas.width, bufferCanvas.height);
				}
			}
		}
	};

	return Render;

});